package com.cfs.svcimpl.sys;

import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Context;

import com.cfs.dao.sys.UserDao;
import com.cfs.svc.sys.UserService;
import com.cfs.vo.Condition;
import com.cfs.vo.Pager;
import com.cfs.vo.Res;
import com.cfs.po.sys.User;
import com.util.CONST;

/**
 *	用户管理实现类
 *	@author SDZJ
 * 	@since 2015-06-11
 * 
 *	@version 1.0
 */
public class UserServiceImpl implements UserService {

	@Context
	private ServletContext cxt;
	private UserDao dao;
	public UserDao getDao() {
		return dao;
	}

	public void setDao(UserDao dao) {
		this.dao = dao;
	}

	@Override
	public Res<User> add(User u) {
		Res<User> res = new Res<User>();
		try{
			dao.insert(u);
			res.setObj(u);
		}catch(Exception e){
			e.printStackTrace();
			res.setCode(-1);
			res.setMsg(e.getLocalizedMessage());
		}

		return res;
	}

	@Override
	public Integer deleteById(Long id) {
		return dao.delete(id);
	}

	@Override
	public Res<User> update(User u) {
		Res<User> res = new Res<User>();
		try{
			dao.update(u);
			res.setObj(u);
		}catch(Exception e){
			e.printStackTrace();
			res.setCode(-1);
			res.setMsg(e.getLocalizedMessage());
		}

		return res;
	}

	@Override
	public Long updatePass(User u) {
		User list = dao.getCheckPass(u.getName(), u.getPass());
		if (list != null) {
			return dao.updPass(u.getId(), u.getPass_new());
		} else {
			System.out.println("原始密码与数据库中不一致！");
			return (long) 0;
		}
	}

	@Override
	public Res<User> get(Long id) {
		Res<User> res = new Res<User>();
		try{
			res.setObj(dao.getById(id));
		}catch(Exception e){
			e.printStackTrace();
			res.setCode(-1);
			res.setMsg(e.getLocalizedMessage());
		}

		return res;
	}

	@Override
	public Res<User> get(HttpServletRequest req) {
		Res<User> res = new Res<User>();
		try{
			res.setObj( (User) req.getSession().getAttribute(CONST.SESSION_USER));
		}catch(Exception e){
			e.printStackTrace();
			res.setCode(-1);
			res.setMsg(e.getLocalizedMessage());
		}

		return res;
	}

	public Res<User> list(Condition c) {
		Res<User> res = new Res<User>();
		try{
			Pager p = c.getP() == null ? new Pager() : c.getP();
			p.resetTotalR(dao.queryRows(c));
			res.setP(p);
			res.setList(dao.list(c));
		}catch(Exception e){
			e.printStackTrace();
			res.setCode(-1);
			res.setMsg(e.getLocalizedMessage());
		}

		return res;
	}
}
